import datetime

from django.shortcuts import render, get_object_or_404
from django.http import Http404
from django.views.generic.dates import DayArchiveView
from django.utils import timezone
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.db.models import Prefetch

from basicinfo.models import Station
from ..models import ShiftSchedule, StationDataLog
from ..forms import StationDataLogModelForm


class StationDataLogDayArchiveView(DayArchiveView):
    queryset = StationDataLog.objects.all()
    ordering = ['log_date', ]
    context_object_name = 'datalog_list'
    date_field = "log_date"
    month_format = '%m'
    allow_empty = True
    allow_future = False

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(StationDataLogDayArchiveView, self).get_context_data(**kwargs)
        log_date = context.get('day')
        station_id_list = self.queryset.filter(log_date=log_date).values('station_id')
        station_list = Station.objects.exclude(pk__in=station_id_list)
        schedule = get_object_or_404(ShiftSchedule, duty_date=log_date)
        now = datetime.datetime.now()
        log_datetime = datetime.datetime.combine(log_date, datetime.time(hour=0, minute=0, second=0))
        deadline = datetime.timedelta(hours=34)
        startline = datetime.timedelta(seconds=0)

        if now - log_datetime < startline:
            out_deadline = True
            is_future = True
        elif now - log_datetime <= deadline:
            out_deadline = False
            is_future = False
        else:
            out_deadline = True
            is_future = False

        context.update({
            'schedule': schedule,
            'station_list': station_list,
            'mode': 2,
            'out_deadline': out_deadline,
            'is_future': is_future,
        })
        return context


def station_datalog_list_by_day(request, year, month, day):
    template_name = 'logs/station_datalog_list_by_day.html'
    try:
        log_date = datetime.date(year=year, month=month, day=day)
    except ValueError:
        raise Http404("日期格式不正确！")

    log_datetime = datetime.datetime.combine(log_date, datetime.time(hour=0, minute=0, second=0))
    next_datetime = log_datetime + datetime.timedelta(days=1)

    now = datetime.datetime.now()
    deadline = datetime.datetime.combine(now.date(), datetime.time(hour=10, minute=0, second=0))

    # if now > deadline and next_datetime < deadline:
    #     raise Http404('{}的日志填报已过期！'.format(log_date))

    # if log_datetime > deadline:
    #     raise Http404('{}的日志还不能填报！'.format(log_date))

    # datalog_list = StationDataLog.objects.filter(log_date=log_date)
    datalog_list = StationDataLog.objects.filter(log_date=log_date)
    station_list = Station.objects.prefetch_related(Prefetch('datalogs', queryset=datalog_list))

    schedule = get_object_or_404(ShiftSchedule, duty_date=log_date)

    return render(request, template_name=template_name,
                  context={'log_date': log_date, 'schedule': schedule,
                           # 'datalog_list': datalog_list,
                           'station_list': station_list,
                           'mode': 3})


def save_station_datalog(request, context, template_name):
    data = dict()
    form = context.get('form', None)

    if request.method == 'POST':
        if form.is_valid():
            station_datalog = form.save(commit=False)
            station_datalog.online_continuous_rate = station_datalog.get_online_continuous_rate

            if station_datalog.pk is None:
                if request.user:
                    station_datalog.created_by = request.user
                station_datalog.created_at = timezone.now()
            else:
                if request.user:
                    station_datalog.updated_by = request.user
                station_datalog.last_updated = timezone.now()

            station_datalog.save()

            data['form_is_valid'] = True
            log_date = station_datalog.log_date

            schedule = get_object_or_404(ShiftSchedule, duty_date=log_date)
            datalog_list = StationDataLog.objects.filter(log_date=station_datalog.log_date)
            print(log_date)
            print(datalog_list)
            station_list = Station.objects.prefetch_related(Prefetch('datalogs', queryset=datalog_list))

            data['html_station_datalog_list'] = render_to_string(
                'logs/includes/partial_station_datalog_list.html',
                {
                    'log_date': log_date,
                    'schedule': schedule,
                    # 'datalog_list': datalog_list,
                    'station_list': station_list,
                    # 'mode': 3,
                })
        else:
            data['form_is_valid'] = False

    # context = {'form': form, }

    data['html_form'] = render_to_string(template_name, context, request=request)
    return JsonResponse(data)


def add_station_datalog(request, station_pk, year, month, day, is_auto=0):
    try:
        log_date = datetime.date(year=year, month=month, day=day)
    except ValueError:
        raise Http404("日期格式不正确！")

    station = Station.objects.get(pk=station_pk)
    log_datetime = datetime.datetime.combine(log_date, datetime.time(hour=0, minute=0, second=0))
    next_log_datetime = log_datetime + datetime.timedelta(days=1)
    initial = {
        'station': station,
        'log_date': log_date,
        'online_interrupt_start': log_datetime,
        'online_interrupt_end': next_log_datetime,
        'online_interrupt_duration': 0.0,
    }

    if request.method == 'POST':
        form = StationDataLogModelForm(request.POST, initial=initial, is_auto=is_auto)
    else:
        form = StationDataLogModelForm(initial=initial, is_auto=is_auto)

    context = {'form': form,
               'station': station,
               'log_date': log_date,
               'is_auto': is_auto,
               }

    return save_station_datalog(request, context, 'logs/includes/partial_station_datalog_form.html')


def update_station_datalog(request, pk, is_auto=0):
    instance = StationDataLog.objects.get(pk=pk)

    station = instance.station
    log_date = instance.log_date
    log_datetime = datetime.datetime.combine(log_date, datetime.time(hour=0, minute=0, second=0))
    next_log_datetime = log_datetime + datetime.timedelta(days=1)

    initial = {}

    if is_auto == 1:
        initial.update({
            'online_interrupt_start': log_datetime,
            'online_interrupt_end': next_log_datetime,
            'online_interrupt_duration': 0.0,
        })

    if request.method == 'POST':
        form = StationDataLogModelForm(request.POST, instance=instance, initial=initial, is_auto=is_auto)
    else:
        form = StationDataLogModelForm(instance=instance, initial=initial, is_auto=is_auto)

    context = {'form': form,
               'station': station,
               'log_date': log_date,
               'is_auto': is_auto,
               }

    return save_station_datalog(request, context, 'logs/includes/partial_station_datalog_form.html')
